/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.connector.rpc;

import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.je.common.base.redis.service.RedisCache;
import org.apache.servicecomb.provider.pojo.RpcSchema;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import java.util.List;
import java.util.Set;

@RpcSchema(schemaId = "connectionRegistryRpcService")
public class ConnectionRegistryRpcServiceImpl implements ConnectionRegistryRpcService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RedisCache redisCache;

    @Override
    public boolean exist(String connectionId) {
        Set<String> keys =redisCache.getKeys(String.format(APP_CONNECTION_MAP_KEY_TEMPLAT,"*"));
        if(keys == null || keys.isEmpty()){
            return false;
        }
        boolean flag = false;
        for (Object eachKey:keys) {
            flag = redisTemplate.opsForSet().isMember(eachKey,connectionId);
            if(flag){
                break;
            }
        }
        return flag;
    }

    @Override
    public void putApp(String appId) {
        redisTemplate.opsForSet().add(APP_MAP_KEY,appId);
    }

    @Override
    public void putAppAndConnectId(String appId, String connectorId) {
        redisTemplate.opsForSet().add(String.format(APP_CONNECTION_MAP_KEY_TEMPLAT,appId),connectorId);
    }

    @Override
    public void putUserAndConnectorId(String userId,String deviceId, String connectorId) {
        redisTemplate.opsForValue().set(String.format(USER_CONNECTION_MAP_KEY_TEMPLAT,userId,deviceId),connectorId);
    }

    @Override
    public String getAppIdByConnector(String connectorId) {
        Set<String> keys = redisCache.getKeys(String.format(APP_CONNECTION_MAP_KEY_TEMPLAT,"*"));
        if(keys == null || keys.isEmpty()){
            return null;
        }

        Set<Object> connectorIdValues;
        for (Object eachKey:keys) {
            connectorIdValues = redisTemplate.opsForSet().members(eachKey);
            if(connectorIdValues == null || connectorIdValues.isEmpty()){
                continue;
            }
            String appId = eachKey.toString().substring(APP_CONNECTION_MAP_KEY_PREFIX.length());
            for (Object eachConnectorId : connectorIdValues) {
                if(connectorId.equals(eachConnectorId)){
                    return appId;
                }
            }
        }
        return null;
    }

    @Override
    public String getAppIdByUser(String userId,String deviceId) {
        if(Strings.isNullOrEmpty(deviceId)){
            deviceId = "web";
        }
        Object connectorObj = redisTemplate.opsForValue().get(String.format(USER_CONNECTION_MAP_KEY_TEMPLAT,userId,deviceId));
        if(connectorObj == null){
            return null;
        }
        return getAppIdByConnector(connectorObj.toString());
    }

    @Override
    public List<String> getAllApps() {
        Set<Object> result = redisTemplate.opsForSet().members(APP_MAP_KEY);
        if(result == null || result.isEmpty()){
            return null;
        }
        List<String> appList = Lists.newArrayList();
        result.forEach(each -> {
            if(each != null){
                appList.add(each.toString());
            }
        });
        return appList;
    }

    @Override
    public List<String> getAppConnectors(String appId) {
        Set<Object> connectorSet = redisTemplate.opsForSet().members(String.format(APP_CONNECTION_MAP_KEY_TEMPLAT,appId));
        if(connectorSet == null || connectorSet.isEmpty()){
            return null;
        }
        List<String> connectorList = Lists.newArrayList();
        for (Object each : connectorSet) {
            if(each != null){
                connectorList.add(each.toString());
            }
        }
        return connectorList;
    }

    @Override
    public long size() {
        Set<String> keys = redisCache.getKeys(String.format(APP_CONNECTION_MAP_KEY_TEMPLAT,"*"));
        if(keys == null || keys.isEmpty()){
            return 0;
        }
        long result = 0L;
        for (Object eachKey:keys) {
            result += redisTemplate.opsForSet().size(eachKey);
        }
        return result;
    }



}
